package com.yunhe.option.service.base.impl;

import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.util.QueryUtil;
import com.yunhe.common.util.StringUtil;
import com.yunhe.option.domain.base.SafetyGrade;
import com.yunhe.option.domain.base.SafetyGrade;
import com.yunhe.option.repository.base.SafetyGradeRepository;
import com.yunhe.option.service.base.SafetyGradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @ClassName SafetyGradeServiceImpl
 * @Description 安全隐患评估类型服务实现
 * @Author HeTao
 * @Date 2020/11/3 14:25
 * @Version 1.0
 **/
@Service
public class SafetyGradeServiceImpl implements SafetyGradeService {

    @Autowired
    private SafetyGradeRepository safetyGradeRepository;

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public SafetyGrade createSafetyGrade(SafetyGrade safetyGrade)
            throws UniqueConstraintsException, ArgumentErrorException {
        safetyGrade.setId(null);
        processBeforeSave(safetyGrade);
        return safetyGradeRepository.save(safetyGrade);
    }

    /**
     * 安全隐患评估类型入库前校验
     * @param safetyGrade
     * @throws UniqueConstraintsException
     * @throws ArgumentErrorException
     */
    private void processBeforeSave(SafetyGrade safetyGrade) throws UniqueConstraintsException, ArgumentErrorException {
        //判断安全隐患评估类型代码、编号、标题是否为空
        if (safetyGrade.getCode() == null
                || StringUtil.isEmpty(safetyGrade.getName())
                || StringUtil.isEmpty(safetyGrade.getTitle())) {
            throw new ArgumentErrorException("安全隐患评估类型代码、编号、标题不能为空");
        }
        //判断代码是否已存在
        SafetyGrade safetyGradeByCode = this.findByCode(safetyGrade.getCode());
        if (safetyGradeByCode != null) {
            if (safetyGrade.getId() == null || safetyGradeByCode.getId().longValue() != safetyGrade.getId().longValue()) {
                throw new UniqueConstraintsException("该安全隐患评估类型代码已存在");
            }
        }
        //判断编号是否已存在
        SafetyGrade typeByName = this.findByName(safetyGrade.getName());
        if (typeByName != null) {
            if (safetyGrade.getId() == null || typeByName.getId().longValue() != safetyGrade.getId().longValue()) {
                throw new UniqueConstraintsException("该安全隐患评估类型编号已存在");
            }
        }
        //如果序号为空，则默认为代码
        if (safetyGrade.getSn() == null && safetyGrade.getCode() != null) {
            safetyGrade.setSn(safetyGrade.getCode());
        }
    }

    private SafetyGrade findByName(String name) {
        return safetyGradeRepository.findByName(name);
    }

    private SafetyGrade findByCode(Long code) {
        return safetyGradeRepository.findByCode(code);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void deleteById(Long id) {
        safetyGradeRepository.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public SafetyGrade updateSafetyGrade(SafetyGrade safetyGrade) throws ObjectNotFoundException, UniqueConstraintsException, ArgumentErrorException {
        boolean exists = safetyGrade.getId() != null && safetyGradeRepository.existsById(safetyGrade.getId());
        if (!exists) {
            throw new ObjectNotFoundException("找不到ID为" + safetyGrade.getId() + "的安全隐患评估类型");
        }
        processBeforeSave(safetyGrade);
        return safetyGradeRepository.save(safetyGrade);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public Iterable<SafetyGrade> findSafetyGrades() {
        return safetyGradeRepository.findAll(QueryUtil.defaultSort());
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public SafetyGrade updateSafetyGrade(Long id, Long code, String name, String title, Long sn, Boolean activity)
            throws ObjectNotFoundException, UniqueConstraintsException, ArgumentErrorException {
        SafetyGrade safetyGrade = this.findBySafetyGradeId(id);
        if (safetyGrade == null) {
            throw new ObjectNotFoundException("找不到ID为" + id + "的安全隐患评估类型");
        }
        Optional.ofNullable(code).ifPresent(safetyGrade::setCode);
        Optional.ofNullable(name).ifPresent(safetyGrade::setName);
        Optional.ofNullable(title).ifPresent(safetyGrade::setTitle);
        Optional.ofNullable(sn).ifPresent(safetyGrade::setSn);
        Optional.ofNullable(activity).ifPresent(safetyGrade::setActivity);
        processBeforeSave(safetyGrade);
        return safetyGradeRepository.save(safetyGrade);
    }

    private SafetyGrade findBySafetyGradeId(Long id) {
        Optional<SafetyGrade> SafetyGradeOptional = safetyGradeRepository.findById(id);
        SafetyGrade SafetyGrade = null;
        if(SafetyGradeOptional.isPresent()){
            SafetyGrade = SafetyGradeOptional.get();
        }
        return SafetyGrade;
    }
}
